package com.sskj.xyft.market;

import android.os.Bundle;
import android.text.TextUtils;

import com.github.tifezh.kchartlib.chart.BaseKChartAdapter;
import com.github.tifezh.kchartlib.chart.KChartView;
import com.github.tifezh.kchartlib.chart.draw.MainDraw;
import com.github.tifezh.kchartlib.chart.formatter.DateLFormatter;
import com.github.tifezh.kchartlib.chart.formatter.TimeFormatter;
import com.sskj.xyft.MVPFragment;
import com.sskj.xyft.R;
import com.sskj.xyft.market.bean.Stock;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * @author Hey
 * Create at  2019/03/21
 */
public class ChartFragment extends MVPFragment<ChartPresenter> {
    @BindView(R.id.minute_kchartview)
    KChartView mMinuteKChartView;  // K线
    private KChartAdapter mAdapter;
    private String goodsType;
    private String code;
    private boolean mIsMinute;
    private Disposable mDisposable;
    private boolean isLoading;
    public String socketPrice;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_chart;
    }

    public static ChartFragment newInstance(String code, String goodsType, boolean isMinute) {
        ChartFragment fragment = new ChartFragment();
        Bundle bundle = new Bundle();
        bundle.putString("code", code);
        bundle.putString("goodsType", goodsType);
        bundle.putBoolean("isMinute", isMinute);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public ChartPresenter getPresenter() {
        return new ChartPresenter();
    }

    @Override
    public void initView() {
        code = getArguments().getString("code");
        goodsType = getArguments().getString("goodsType");
        mIsMinute = getArguments().getBoolean("isMinute");
        mPresenter.getStock(code, goodsType, true);
        //0 获取五大币数据
        mMinuteKChartView.setMainDownColor(R.color.color_999999);
        mMinuteKChartView.setBackgroundColor(color(R.color.white));
        mMinuteKChartView.setMa5Color(getResources().getColor(R.color.color_fcd));
        mMinuteKChartView.setMa10Color(getResources().getColor(R.color.color_6cd));
        mMinuteKChartView.setMa20Color(getResources().getColor(R.color.color_c71));
        mMinuteKChartView.showLoading();
        mMinuteKChartView.setDrawTabView(true);
        mMinuteKChartView.setMainUpColor(R.color.red);  // 设置k线颜色 涨
        mMinuteKChartView.setMainDownColor(R.color.green); // 设置k线颜色 跌
        mMinuteKChartView.setGridLineColor(getResources().getColor(R.color.line));
        mMinuteKChartView.setGridLineWidth(1f);
        mMinuteKChartView.setGridRows(2);
        mMinuteKChartView.setGridColumns(2);
        mMinuteKChartView.setVolumeMaGone(true);
        mMinuteKChartView.setTextColor(color(R.color.hint));
        mMinuteKChartView.setShader(color(R.color.fillColor), color(R.color.fillTopColor), color(R.color.fillEndColor), 2000);
        ((MainDraw) mMinuteKChartView.getMainDraw()).setSelectorTextColor(color(R.color.white));
        mMinuteKChartView.setBreathColor(color(R.color.tabColor));
        if (mIsMinute) {
            mMinuteKChartView.setDrawMinuteStyle(true);
            mMinuteKChartView.setDateTimeFormatter(new TimeFormatter());
        } else {
            mMinuteKChartView.setDateTimeFormatter(new DateLFormatter());
        }
        mAdapter = new KChartAdapter();
        mMinuteKChartView.setAdapter(mAdapter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mAdapter.getCount() <= 0) {
            mPresenter.getStock(code, goodsType, true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }


    public void setChart(List<Stock> stockList, boolean update) {
        if (mMinuteKChartView != null) {
            mMinuteKChartView.hideLoading();
            if (stockList == null) {
                stockList = new ArrayList<>();
            }
            Collections.reverse(stockList);
            DataHelper.calculate(stockList);
            mAdapter.datas.clear();
            if (!TextUtils.isEmpty(socketPrice)) {
                if (stockList.size() > 0) {
                    stockList.get(stockList.size() - 1).setClosePrice(Float.parseFloat(socketPrice));
                }
            }
            mAdapter.addFooterData(stockList);
            isLoading = false;
        }
    }

    public void upDate(Stock stock) {
        ArrayList<Stock> stocks = new ArrayList<>();
        stocks.add(stock);
        DataHelper.calculate(stocks);
        if (mAdapter != null && mAdapter.getCount() > 0) {
            Stock lastItem = (Stock) mAdapter.getItem(mAdapter.getCount() - 1);
            Long newTime = stock.getTimestamp() / 1000;
            Long lastTime = lastItem.getTimestamp() / 1000;
            long time = newTime - lastTime;
            boolean add = false;
            if (goodsType.equals("minute")) {
                add = time >= 1 * 60;
            } else if (goodsType.equals("minute30")) {
                add = time >= 30 * 60;
            } else if (goodsType.equals("minute60")) {
                add = time >= 60 * 60;
            } else if (goodsType.equals("minute120")) {
                add = time >= 120 * 60;
            } else if (goodsType.equals("day")) {
                add = time >= 24 * 60 * 60;
            } else if (goodsType.equals("minute240")) {
                add = time >= 4 * 60 * 60;
            }
            socketPrice = stock.getClosePrice() + "";
            if (add && !isLoading) {
                isLoading = true;
                mAdapter.getDatas().add(stock);
                mAdapter.notifyItemInsertedToLast();
                mPresenter.getStock(code, goodsType, false);
            }
            mAdapter.notifyLastItemChanged(Float.parseFloat(socketPrice));
        }

    }


    @Override
    public void initData() {

    }

    public KChartView getKChartView() {
        return mMinuteKChartView;
    }


    /**
     * 数据适配器
     * Created by tifezh on 2016/6/18.
     */

    public class KChartAdapter extends BaseKChartAdapter {

        private List<Stock> datas = new ArrayList<>();

        public KChartAdapter() {

        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            if (position < 0) {
                position = 0;
            }
            return datas.get(position);
        }

        @Override
        public Date getDate(int position) {
            try {
                return new Date(datas.get(position).getTimestamp() * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public List<Stock> getDatas() {
            return datas;
        }

        /**
         * 向头部添加数据
         */
        public void addHeaderData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(data);
                notifyItemRangeInsertedToLast();
            }
        }


        /**
         * 向头部添加一条数据
         * <p>
         * public void addHeaderItemData(Stock obj) {
         * if (obj != null) {
         * datas.add(obj);
         * notifyDataSetChanged();
         * }
         * }
         * <p>
         * /**
         * 向尾部添加数据
         */
        public void addFooterData(List<Stock> data) {
            if (data != null && !data.isEmpty()) {
                datas.addAll(0, data);
                notifyDataSetChanged();
            }
        }

        /**
         * 改变某个点的值
         *
         * @param position 索引值
         */
        public void changeItem(int position, Stock data) {
            datas.set(position, data);
            notifyDataSetChanged();
        }

    }

}
